var express = require('express');
var router = express.Router();
var {
    zhongModel,
    xiModel,
    permissionModel,
    // drug_numModel,
    // zhong_signeturModel,
    // xi_signeturModel,
    managementModel,//词条管理
    authorityModel,
    groupingModel,
    diagnosticModel,//常用诊断管理
    diagnostic_cateModel,
    dictionaryModel,//字典管理
    dictionary_cateModel,
    parameterModel,//参数配置
    log_onsModel,//登录日志
    journalModel,//操作日志
} = require('../model/model')

var Mock = require('mockjs')
//登录日志
const loginHistory = Mock.mock({
    'data|20':[
        {
            'name':'@csentence(3,8)',
            'time':'@datetime',
            'ip':'@ip',
            'mac|1':['手机','电脑'],
            'login|1':['Chrome浏览器','谷歌浏览器']
        }
    ]
})
//操作日志
const journalHistory = Mock.mock({
    'data|20': [
        {
            'module|1': ["患者登记", "医生登记"],
            'cate|1': ["新增", "删除", "修改", "查看"],
            "operator": '@csentence(3,8)',
            "ipAddress": '@ip',
            'operationTime': '@datetime',
            'requestUrl': '@ip',
            'requestMethod|1': ['POST', 'GET', 'DELETE'],
            'operationMethod|1': ['create', 'delete', 'update', 'find'],
            'requestParams': {
                "admin": false,
                "createBy": "admin",
                "nickName": "@integer(10000, 99999)", // 随机数字
                "params": {},
                "postIds": [],
                "roleIds": [],
                "status": "0",
                "userId": "@integer(1, 1000)", // 随机userId
                "userName": "@integer(100000, 999999)" // 随机用户名
            },
            'responseTime|1': '@integer(100, 1000)' // 生成100到1000毫秒之间的随机数
        }
    ]
});


// journalModel.create(journalHistory.data)

router.get('/zhonglogin',async(req,res)=>{

    res.send(
        {
            code:200,
            zhonglogin:loginHistory.data
        }
    )
})
router.get('/zhongList', async (req, res) => {
    let zhongList = await zhongModel.find()

    res.send({
        code: 200,
        zhongList
    })
})

router.get('/xiList', async (req, res) => {
    let xiList = await xiModel.find()

    res.send({
        code: 200,
        xiList
    })
})

router.get('/permissionList', async (req, res) => {
    let permissionList = await permissionModel.find()

    res.send({
        code: 200,
        permissionList
    })
})

router.get('/drug_numList', async (req, res) => {
    let drug_numList = await drug_numModel.find()

    res.send({
        code: 200,
        drug_numList
    })
})

router.get('/zhong_signeturList', async (req, res) => {
    let zhong_signeturList = await zhong_signeturModel.find()

    res.send({
        code: 200,
        zhong_signeturList
    })
})

router.get('/xi_signeturList', async (req, res) => {
    let xi_signeturList = await xi_signeturModel.find()

    res.send({
        code: 200,
        xi_signeturList
    })
})

router.get('/managementList', async (req, res) => {
    let { page, pagesize, name, state } = req.query

    let arr = [{}]

    let nameReg = new RegExp(name)
    if (name) arr.push({
        name: nameReg
    })

    if (state) arr.push({
        state
    })
    console.log(name, state);
    let managementList = await managementModel.find({ $and: arr }).populate('authority').populate('grouping')
    managementList = await managementModel.find({ $and: arr }).populate('authority').populate('grouping').skip((page - 1) * pagesize).limit(pagesize)
    let total = await managementModel.find({ $and: arr }).countDocuments()

    res.send({
        code: 200,
        managementList,
        total
    })
})
router.get('/authorityList', async (req, res) => {
    let authorityList = await authorityModel.find()
    console.log(authorityList);

    res.send({
        code: 200,
        authorityList
    })
})

router.get('/groupingList', async (req, res) => {
    let groupingList = await groupingModel.find()

    res.send({
        code: 200,
        groupingList
    })
})

router.post('/groupingadd', async (req, res) => {
    await groupingModel.create(req.body)

    res.send({
        code: 200,
    })
})
router.post('/groupingupd', async (req, res) => {
    let body = req.body
    let _id = body._id
    await groupingModel.updateOne({ _id: _id }, body)

    res.send({
        code: 200,
    })
})
router.delete('/groupingdel', async (req, res) => {
    let { _id } = req.query
    await groupingModel.deleteOne({ _id: _id })

    res.send({
        code: 200,
    })
})

router.post('/zhongadd', async (req, res) => {
    let body = req.body
    await zhongModel.create(body)

    res.send({
        code: 200
    })
})

router.post('/xiadd', async (req, res) => {
    let body = req.body
    await xiModel.create(body)

    res.send({
        code: 200
    })
})

router.post('/permissionadd', async (req, res) => {
    let body = req.body
    await permissionModel.create(body)

    res.send({
        code: 200
    })
})

router.post('/managementadd', async (req, res) => {
    let body = req.body
    console.log(body);

    await managementModel.create(body)

    res.send({
        code: 200
    })
})

router.post('/managementupd', async (req, res) => {
    let body = req.body
    let _id = body._id
    console.log(body)

    await managementModel.updateOne({ _id: _id }, body)

    res.send({
        code: 200
    })
})

router.delete('/managementdel', async (req, res) => {
    let { _id } = req.query

    await managementModel.deleteOne({ _id: _id })

    res.send({
        code: 200
    })
})

router.post('/authorityadd', async (req, res) => {
    let body = req.body
    await authorityModel.create(body)

    res.send({
        code: 200
    })
})

router.post('/groupingadd', async (req, res) => {
    let body = req.body
    await groupingModel.create(body)

    res.send({
        code: 200
    })
})

// // 获取诊断列表，按分类过滤
// router.get('/diagnosticList', async (req, res) => {
//     const { category } = req.query; // 获取前端传来的分类
//     try {
//       let arr = [{}];
//       if (category) arr.push({
//         category:category // 如果有分类，进行分类过滤
//       })
//       const diagnosticList = await Diagnostic.find({$and:arr}); // 查询符合条件的诊断数据
//       res.json({ code: 200, diagnosticList });
//     } catch (error) {
//       res.status(500).json({ code: 500, message: '服务器错误' });
//     }
//   });

router.get('/diagnosticList', async (req, res) => {
    let diagnosticList = await diagnosticModel.find()

    res.send({
        code: 200,
        diagnosticList
    })
})

router.post('/diagnosticadd', async (req, res) => {
    await diagnosticModel.create(req.body)

    res.send({
        code: 200,
    })
})

router.get('/diagnostic_cateList', async (req, res) => {
    let diagnostic_cateList = await diagnostic_cateModel.find()

    res.send({
        code: 200,
        diagnostic_cateList
    })
})

router.post('/diagnostic_cateadd', async (req, res) => {
    await diagnostic_cateModel.create(req.body)

    res.send({
        code: 200,
    })
})

router.get('/dictionaryList', async (req, res) => {
    let { page, pagesize, name, dictionary_cate } = req.query

    let arr = [{}]

    let nameReg = new RegExp(name)
    if (name) arr.push({
        name: nameReg
    })

    if (dictionary_cate) arr.push({
        dictionary_cate: dictionary_cate
    })

    // let dictionaryList = await dictionaryModel.find({$and:arr})
    let dictionaryList = await dictionaryModel.find({ $and: arr })
    dictionaryList = await dictionaryModel.find({ $and: arr }).skip((page - 1) * pagesize).limit(pagesize)
    let total = await dictionaryModel.find({ $and: arr }).countDocuments()

    res.send({
        code: 200,
        dictionaryList,
        total
    })
})

router.post('/dictionaryadd', async (req, res) => {
    await dictionaryModel.create(req.body)

    res.send({
        code: 200,
    })
})

router.post('/dictionaryupd', async (req, res) => {
    let body = req.body
    let _id = body._id
    console.log(body)

    await dictionaryModel.updateOne({ _id: _id }, body)

    res.send({
        code: 200
    })
})


router.get('/dictionary_cateList', async (req, res) => {
    let { name } = req.query
    let arr = [{}]

    let nameReg = new RegExp(name)
    if (name) arr.push({
        name: nameReg
    })
    let dictionary_cateList = await dictionary_cateModel.find({ $and: arr })

    res.send({
        code: 200,
        dictionary_cateList
    })
})

router.post('/dictionary_cateadd', async (req, res) => {
    await dictionary_cateModel.create(req.body)

    res.send({
        code: 200,
    })
})

router.get('/parameterList', async (req, res) => {
    let { name, state, page, pagesize, can_num } = req.query
    let arr = [{}]

    let nameReg = new RegExp(name)
    let can_numReg = new RegExp(can_num)
    if (name) arr.push({
        name: nameReg
    })
    if (can_num) arr.push({
        can_num: can_numReg
    })
    if (state) arr.push({
        state
    })

    console.log(name, state, page, pagesize, can_num);
    
    let parameterList = await parameterModel.find({ $and: arr })
    parameterList = await parameterModel.find({ $and: arr }).skip((page - 1) * pagesize).limit(pagesize)
    let total = await parameterModel.find({ $and: arr }).countDocuments()

    res.send({
        code: 200,
        parameterList,
        total
    })
})

router.post('/parameteradd', async (req, res) => {
    await parameterModel.create(req.body)

    res.send({
        code: 200,
    })
})


router.delete('/parameterdel', async (req, res) => {
    let {_id} = req.query

    await parameterModel.deleteOne({_id:_id})

    res.send({
        code: 200,
    })
})


router.post('/parameterupd', async (req, res) => {
    let body = req.body
    let _id = body._id
    console.log(body)

    await parameterModel.updateOne({ _id: _id }, body)

    res.send({
        code: 200
    })
})

router.get('/log_on_List', async (req, res) => {
    let { name, time,page,pagesize } = req.query
    let arr = [{}]

    let nameReg = new RegExp(name)
    let timeReg = new RegExp(time)
    if (name) arr.push({
        name: nameReg
    })
    if (time) arr.push({
        time: timeReg
    })

    console.log(name, page, pagesize, time);
    
    let log_on_List = await log_onsModel.find({ $and: arr })
    log_on_List = await log_onsModel.find({ $and: arr }).skip((page - 1) * pagesize).limit(pagesize)
    let total = await log_onsModel.find({ $and: arr }).countDocuments()

    res.send({
        code: 200,
        log_on_List:log_on_List,
        total
    })
})

router.post('/log_onadd', async (req, res) => {
    console.log(req.body);
    
    await log_onsModel.create(req.body)

    res.send({
        code: 200,
    })
})

router.get('/journalList', async (req, res) => {
    let { model, operator,operationTime,page,pagesize } = req.query
    let arr = [{}]
    let modelReg = new RegExp(model)
    let operatorReg = new RegExp(operator)
    let operationTimeReg = new RegExp(operationTime)

    if (model) arr.push({
        model: modelReg
    })
    if (operator) arr.push({
        operator: operatorReg
    })
    if (operationTime) arr.push({
        operationTime: operationTimeReg
    })

    console.log(model, page, pagesize, operator,operationTime);
    
    let journalList = await journalModel.find({ $and: arr })
    journalList = await journalModel.find({ $and: arr }).skip((page - 1) * pagesize).limit(pagesize)
    let total = await journalModel.find({ $and: arr }).countDocuments()

    res.send({
        code: 200,
        journalList,
        total
    })
})

router.post('/journaladd', async (req, res) => {
    console.log(req.body);
    
    await journalModel.create(req.body)

    res.send({
        code: 200,
    })
})

module.exports = router;